<!-- 表格组件 -->
<template>
    <div class="table">
        <el-table :data="tableData" stripe :border="true" style="width: 100%" ref="multipleTable"
            :header-row-class-name="() => 'table-header'" :max-height="props.maxHeight" v-loading="loading"
            @selection-change="selectChange" @row-click="changeTable" :row-key="rowKey" class="custom-loading-svg"
            size="default">
            <el-table-column :reserve-selection="true" :type="!props.elTable_Options.selection ? 'selection' : 'index'"
                width="45" lable="#" />
            <el-table-column
                v-for="(item, index) in filterLikeFields(props.elTable_Options.eltableArr, props.preferenceFiles)"
                :key="item.prop + index" :width="item.width" :prop="item.prop" :label="item.label"
                :fixed="item.fixed ? item.fixed : false" show-overflow-tooltip
                :sortable="item.sortable ? 'custom' : false">
                <template v-slot="scope">
                    <!-- linkTo 蓝色链接跳转 -->
                    <span class="linkTo" v-if="item.columType == 'linkTo'"
                        @click="handleClick(scope.row, !item.index ? 3 : item.index, scope.$index, item)">{{
                            scope.row[item.prop] }}</span>
                    <!-- text 文本 -->
                    <span v-if="item.columType == 'text'">{{ scope.row[item.prop] || '-' }}</span>
                    <!-- time 日期 -->
                    <span v-if="item.columType == 'time'">{{ commonV.formatDate(scope.row[item.prop], item.type ?
                        item.type
                        : 'yyyy-MM-dd') }}</span>
                    <!-- arrayKey 取数组里面的值作为字符串显示  人员keyName=real_name -->
                    <div v-if="item.columType == 'arrayKey'">
                        <span v-if="item.opposite">
                            {{ commonV.reverarr(scope.row[item.keyName], item.prop) }}
                        </span>
                        <span v-else>{{ commonV.reverarr(scope.row[item.prop], item.keyName) }}</span>
                    </div>
                    <!-- select 下拉框 筛选下拉框状态匹配  -->
                    <div v-if="item.columType === 'select'">
                        <el-tag v-if="item.tag">
                            {{
                                commonV.matchOption(commonV.statusOption[item.commonVarrName], scope.row[item.prop])
                            }}
                        </el-tag>
                        <span v-else :style="{
                            color: commonV.matchOption(commonV.statusOption[item.commonVarrName], scope.row[item.prop], 'color')
                        }">
                            {{
                                commonV.matchOption(commonV.statusOption[item.commonVarrName], scope.row[item.prop])
                            }}
                        </span>
                    </div>
                    <!-- objKey 对象里的值(值作key) -->
                    <div v-if="item.columType == 'objKey'">
                        <span v-if="!item.opposite">
                            {{ scope.row[item.keyName] ? scope.row[item.keyName][item.prop] : '-' }}
                        </span>
                        <span v-else>
                            {{ scope.row[item.prop] ? scope.row[item.prop][item.keyName] : '-' }}
                        </span>
                    </div>
                    <!-- departmentRole 科室角色展示 -->
                    <div v-if="item.columType == 'departmentRole'">
                        {{ commonV.departroleformat(scope.row[item.prop]) }}
                    </div>
                    <!-- opreatebar 操作栏 -->
                    <div v-if="item.columType == 'opreatebar'" class="operation">
                        <div class="opera-it" v-for="(it, idx) in item.operation" :key="idx">
                            <span v-if="it.disabled" class="operation-btn operation-btn-disabled">{{ it.op_name
                            }}</span>
                            <span v-else class="operation-btn" :style="{ 'background': it.color }"
                                @click="handleClick(scope.row, it.op_index, scope.$index, it)">{{ it.op_name }}</span>
                        </div>
                    </div>
                    <!-- downloadFile 文件下载 -->
                    <div v-if="item.columType == 'downloadFile'">
                        <div v-for="(item2, index2) in scope.row[item.prop]" :key="index2">
                            <a style="color: #20a0ff" :href="item2.url" target="_blank">{{ commonV.varfile(item2.url)
                            }}</a>
                        </div>
                    </div>
                    <!-- elcascaderVal 级联选择器 -->
                    <div v-if="item.columType == 'elcascaderVal'">
                        {{
                            commonV.getCascaderFullValue(scope.row[item.prop], commonV.statusOption[item.commonVarrName])
                        }}
                    </div>
                    <!-- profile 头像 -->
                    <img v-if="item.columType == 'profile'" class="profile" :src="scope.row[item.prop]" alt=""
                        height="30" width="30" />
                    <!-- input 输入框 -->
                    <div v-if="item.columType == 'input'">
                        <el-input size="default" v-model="scope.row[item.prop]" :disabled="item.disabled"
                            v-if="!item.type">
                        </el-input>
                        <el-input-number v-model="scope.row[item.prop]" controls-position="right" :min="1"
                            :max="scope.row[item.prop]" v-if="item.type == 'num'" size="default"></el-input-number>
                    </div>
                    <!-- approveState 审批状态 -->
                    <div v-if="item.columType == 'approveState'">
                        <span v-if="commonV.ifrrandnotnone(scope.row[item.keyName])" :style="{
                            color: commonV.matchOption(commonV.statusOption[item.commonVarrName], scope.row[item.keyName][0][item.prop], 'color')
                        }">
                            {{ commonV.matchOption(commonV.statusOption[item.commonVarrName],
                                scope.row[item.keyName][0][item.prop]) }}
                        </span>
                        <span v-else>-</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination" v-if="props.elTable_Options.ifturnpage !== false">
            <el-pagination background :current-page="state.p" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @current-change="changePage" @size-change="changePageSize" />
        </div>
    </div>
</template>

<script setup>
import { reactive, computed, toRefs, watch, ref } from 'vue'
import commonV from '@/common/index'
// import { loadingSvg } from '@/otherComponent/icons/svg/loading.ts'
import { useCach } from '@/store/cach'
import api from '@/api'

//参数
let props = defineProps({
    elTable_Options: {
        type: Object,
        default: () => {
            return {}
        }
    },
    searchParams: {
        type: Object,
        default: () => {
            return {}
        }
    },
    preferenceFiles: {
        type: Array,
        default: () => {
            []
        }
    },
    maxHeight: {
        type: Number,
        default: () => 460
    }
})

//事件
const emit = defineEmits(['handleClick'])

//数据源
let state = reactive({
    //loading
    loading: false,
    //table数据
    tableData: [],
    //第几页
    p: 1,
    //每页多少条
    size: 10,
    //总条数
    total: 0,
    spanArr: [],
    selection: [],
    currentClickRow: null
})
//解构
let { tableData, total, loading } = toRefs(state)

//唯一key
let rowKey = (row) => {
    return row.id
}

//点击事件
let handleClick = (row, index, orderNum, item) => {
    emit('handleClick', row, index, orderNum, item)
}

//过滤用户喜好字段
let filterLikeFields = (arr = [], target = []) => {
    if (!target.length) {
        return arr
    }

    return arr.filter(it => target.includes(it.prop))
}

let multipleTable = ref(null)
let getTableData = async (row) => {
    state.loading = true
    let params = {}
    // 分页参数
    params.p = state.p
    params.page_size = state.size

    //额外传进来参数
    // if (row) {
    //     for (let key in row) {
    //         params[key] = row[key]
    //     }
    // }

    //上次记录的参数
    if (row) {
        params.p = row.p
        params.page_size = row.size
        state.p = row.p
        state.size = row.size
    }

    // 搜索栏参数 将搜索栏参数通过类型取值
    if (commonV.ifrrandnotnone(props.elTable_Options.searchList)) {
        let searchVal = commonV.formatSearchParams(props.elTable_Options.searchList, props.searchParams)
        params = Object.assign(params, searchVal)
    }

    // 是否有额外查询条件 
    if (props.elTable_Options.addConditions) {
        for (let i = 0; i < props.elTable_Options.addConditions.length; i++) {
            let item = props.elTable_Options.addConditions[i]
            params[item.key] = item.value
        }
    }

    //是否有tab栏切换参数
    if (props.elTable_Options.elMenuArr) {
        let menuname = props.elTable_Options.menuname
        let filter = props.elTable_Options.elMenuArr.filter(it => it.key == menuname)
        if (filter.length) {
            if (filter[0].addConditions) {
                for (let i = 0; i < filter[0].addConditions.length; i++) {
                    let item = filter[0].addConditions[i]
                    params[item.key] = item.value
                }
            }
        }
    }

    let res = await api.getaxiosdata(props.elTable_Options.getwayname, params)
    if (res) {
        //总条数
        let total = res.count || res.length
        state.total = total ? parseInt(total) : 0
        //是否分页
        let tableArr = res.results ? res.results : res
        //列表赋值
        state.tableData = JSON.parse(JSON.stringify(tableArr))

        pageConfig.changeTableInfo(null)
    }
    state.loading = false
}

//重置
let conditionalQuery = () => {
    changePage(1)
}

let pageConfig = useCach()
let isClean = computed(() => pageConfig.isCleanChooseRow)
let initSelectData = computed(() => pageConfig.initChooseRow)

watch(isClean, (val) => {
    if (val) {
        //删除全部
        multipleTable.value.clearSelection()
        state.currentClickRow = null
    }
}, { deep: true })

//初始化选中
watch(initSelectData, (val) => {
    //给选中项赋值
    if (val.selection) {
        //单选
        state.currentClickRow = val.selectArr[0]
        return
    }
    //多选
    val.selectArr.forEach((row) => {
        multipleTable.value.toggleRowSelection(row, undefined)
    })
}, { deep: true })

//选中项改变
let selectChange = (selection) => {
    state.selection = JSON.parse(JSON.stringify(selection))
    pageConfig.changeChooseRow({ 'radio': state.currentClickRow, 'multiple': state.selection })
}

//点击某一项
let changeTable = (row) => {
    //单选
    if (props.elTable_Options.selection) {
        state.currentClickRow = row
        pageConfig.changeChooseRow({ 'radio': row, 'multiple': state.selection })
        return
    }
    let list = JSON.parse(JSON.stringify(state.selection))
    let idx = list.findIndex(i => i.id == row.id)
    idx != -1 ? list.splice(idx, 1) : list.push(row)
    selectChange(list)
    multipleTable.value.toggleRowSelection(row)
}

//切换分页
let changePage = (value) => {
    state.p = value
    getTableData()
}

//切换每页多少条
let changePageSize = (value) => {
    state.size = value
    getTableData()
}

//列表选中项
let getSelection = () => {
    return state.selection
}

//传递出去的事件
defineExpose({ getTableData, conditionalQuery, state, getSelection })

</script>

<style lang="scss" scoped>
.table {
    :deep(.table-header .el-table__cell) {
        background-color: rgb(239, 243, 248);
    }
}

.linkTo {
    color: #0165b4;
    cursor: pointer;
}

.operation {
    display: flex;
    align-items: center;

    .operation-btn {
        padding: 3px 8px;
        line-height: 20px;
        height: 20px;
        margin-right: 5px;
        cursor: pointer;
        text-align: center;
        font-size: 10px;
        color: #ffffff;
        border-radius: 2px;
    }

    .operation-btn-disabled {
        background: #99a9bf;
        cursor: not-allowed
    }
}

.profile {
    border-radius: 50%;
}

.pagination {
    width: calc(100% - 2px);
    margin: 0 auto;
    display: flex;
    padding: 8px 10px;
    justify-content: flex-end;
    align-items: center;
    background-color: #ffffff;
    border-right: 0;
    border-left: 0;
}
</style>